package com.zb.test;

import com.zb.bean.Employee;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8 内置四大核心函数式接口
 *
 *  Consumer<T>:消费者接口
 *      void accept(T t);
 *
 *  Supplier<T>:供给型接口
 *      T get();
 *
 *  Function(T,R):函数型接口
 *      R apply(T t);
 *
 *  Predicate(T):断言型接口
 *      bolean test(T t);
 *
 */
public class JAVA8_3_内置的四大核心函数式接口 {

    //1. Consumber接口测试
    @Test
    public void test1(){
        testConsumber(10000d,(x)-> System.out.println("玩大宝剑消费"+x+"元"));
        testConsumber(200d,x-> System.out.println("看电影消费："+x+"元"));
    }

    //2. Supplier接口测试
    //生成指定个数的随机整数放在一个集合中返回
    @Test
    public void test2(){
        List<Integer> list = testSupplier(10,()->(int)(Math.random()*100));
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }

    //3.Function 接口测试
    @Test
    public void test3(){
        String upStr = testFunction("zhangBin",x->x.toUpperCase());
        System.out.println(upStr);

        String trimStr = testFunction("\t\t\t\t zhangbin   ",x->x.trim());
        System.out.println(trimStr);
    }

    //4. Predicate 接口测试
    //将集合中元素长度大于3的元素过滤出来
    @Test
    public void test4(){
        List<String> list = Arrays.asList("zhangbin","lisi","a","b","ok");
        List<String> newList = testPredicate(list,x->x.length()>3);
        for (String s : newList) {
            System.out.println(s);
        }
    }


    public void testConsumber(Double money, Consumer<Double> consumer){
        consumer.accept(money);
    }
    public List<Integer> testSupplier(Integer count, Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for (Integer i = 0; i < count; i++) {
            list.add(supplier.get());
        }
        return list;
    }
    public String testFunction(String str, Function<String,String> function){
        return function.apply(str);
    }
    public List<String> testPredicate(List<String> list,Predicate<String> predicate){
        List<String> reslist = new ArrayList<>();
        for (String s : list) {
            if(predicate.test(s)){
                reslist.add(s);
            }
        }
        return reslist;
    }

    public static void main(String[] args) {
        List<Employee> list  = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Employee emp = new Employee(i,"aa", (int) (i*Math.random()));
            list.add(emp);
        }
        list.stream().forEach(x->{
            System.out.println(x.getAge());
        });
    }
}
